Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home diretcory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [1]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8350 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [2]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

#Note: I decided to wrap this code into a helper function for later use.
def show_face_cascade(facefile):
    # load color (BGR) image
    img = cv2.imread(facefile)
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)

    # print number of faces detected in the image
    print('Number of faces detected:', len(faces))

    # get bounding box for each detected face
    for (x,y,w,h) in faces:
        # add bounding box to color image
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),8)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.imshow(cv_rgb)
    plt.show()
    
show_face_cascade(human_files[0])
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [3]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

In [4]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
num_faces_human=0
bad_humans=[]
for file in tqdm(human_files_short):
    if face_detector(file):
        num_faces_human += 1
    else:
        bad_humans.append(file)
num_faces_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
    if face_detector(file):
        num_faces_dog += 1
        bad_dogs.append(file)

print(f"{num_faces_human}% of the first 100 human files have a detected human face.")
print(f"{num_faces_dog}% of the first 100 dog files have a detected human face.")
100%|██████████| 100/100 [00:02<00:00, 36.62it/s]
100%|██████████| 100/100 [00:21<00:00,  4.49it/s]
95% of the first 100 human files have a detected human face.
14% of the first 100 dog files have a detected human face.

Actually if you look at some of the dog files in which faces were found, there are actually some human faces in some of them! See:

(note: if you run this yourself then depending on your random seed you may or may not see what I mean here)

In [5]:
for file in bad_dogs: show_face_cascade(file)
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 2
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 2
Number of faces detected: 1

Okay but there are definitely also some bogus faces getting selected out of dog faces or strangely face-like dog-fat-wrinkles.

And here are the few humans who just don't look human enough for the face detector:

In [6]:
for file in bad_humans: show_face_cascade(file)
Number of faces detected: 0
Number of faces detected: 0
Number of faces detected: 0
Number of faces detected: 0
Number of faces detected: 0

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [7]:
### (Optional) 
### TODO: Test performance of anotherface detection algorithm.
### Feel free to use as many code cells as needed.

# Okay, how about appending a face detector to a CNN that was pretrained on ImageNet?

#Let me start by pulling in a pre-trained VGG16 just like in Step 2 below.

import torch
import torchvision.models as models

# define VGG16 model
human_dog_net = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    human_dog_net = human_dog_net.cuda()
    
print(human_dog_net)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): Dropout(p=0.5)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace)
    (5): Dropout(p=0.5)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)

Now let's replace the linear layers at the end by our own classifer. Since all it needs to do in the end is "face" and "not face", it doesn't need to be quite as complex as the current VGG16 classifier.

Since we actually don't have that much data to train on (compared to ImageNet!), we should definitely freeze the convolutional layers of VGG16. Otherwise I would be afraid of overfitting.

In [8]:
from torch import nn

human_dog_net.classifier = nn.Sequential(nn.Linear(25088,4096),
                                          nn.ReLU(),
                                          nn.Dropout(0.3),
                                          nn.Linear(4096,512),
                                          nn.ReLU(),
                                          nn.Dropout(0.3),
                                          nn.Linear(512,3),
                                          nn.LogSoftmax(dim=1),
                                         )

# Freeze parameters in convolutional layers:
for module in human_dog_net.features:
    for param in module.parameters():
        param.requires_grad = False
        
# Need to do this again after defining new classifier module
if use_cuda:
    human_dog_net = human_dog_net.cuda()

Now the human_files and dog_files are a bit misleading to train on, since many of the dog_files contain humans. In the end, we want the app to behave a certain way if it detects a dog, a certain way if it detects a human and no dog, and another way if it detects neither. So there are three classes to deal with here.

Ideally I'd want to train on data that has three labels "there is dog", "there is human and no dog", and "there is no human and no dog". But I don't have data of the third type available, and I would need it to be really varied across all the nonhuman nondog possibilities.

I cannot exclude the third category! To do so would make my dog detector be more likely to detect dogs in the absence of a human, and it would make my human detector more likely to detect humans in the absence of a dog. It would correlate 'dogness' to the absence of a human, and 'humanness' to the absence of a dog.

Finding a varied dataset of nonhuman nondogs is a bit harder than it sounds. The labeled image datasets I can find tend to have some humans showing up in all kinds of different categories. (Makes sense. All photos are taken by humans, and humans like to put themselves in photos.)

Okay I will use the dataset here and use the Haar cascade face detector to clean it up! I downloaded and extracted 101_ObjectCategories.tar.gz. Now let's clean it up of as many human faces as possible. To make things run faster (and to avoid what appeared to be opencv bugs related to the size of the image), I deleted any files bigger than 300K using the following bash command:

find 101_ObjectCategories/ -size +300k -type f -delete

There were only 3 such files anyway. I also want to get rid of all files that explicitly contain dogs, so

rm -rf 101_ObjectCategories/dalmatian/ 101_ObjectCategories/snoopy/

(Even though snoopy is a cartoon dog, he's got to go!)

In [9]:
caltech_files = np.array(glob("101_ObjectCategories/*/*"))
In [10]:
haar_faces=[]
for file in tqdm(caltech_files):
    if face_detector(file):
        haar_faces.append(file)
100%|██████████| 9040/9040 [04:49<00:00, 31.20it/s]
In [ ]:
# Run this cell to save haar_faces list so you don't have to run the above cell to compute it again later.
import pickle
pickle.dump(haar_faces, open( "haar_faces.p", "wb" ))
In [10]:
# Run this cell to load saved haar_faces list if you already produced it before.
import pickle
haar_faces = pickle.load( open( "haar_faces.p", "rb" ) )

I'm going to kick out all the things in the list haar_faces. This does unfortunately kick out a few false faces:

In [11]:
show_face_cascade('101_ObjectCategories/kangaroo/image_0016.jpg')
show_face_cascade('101_ObjectCategories/airplanes/image_0324.jpg')
show_face_cascade('101_ObjectCategories/butterfly/image_0084.jpg')
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1

But the vast majority of things kicked out do actually involve faces, and this does clean up the data quite a bit. We still have a good number of images:

In [12]:
print(len([f for f in caltech_files if f not in haar_faces]))
8006

Now I will define define my own dataloader to simplify the training and testing code later on. The three classes are

  • 0: No human is present and no dog is present.
  • 1: A dog is present. (And possibly also a human)
  • 2: A human is present, and no dog is present.

The dataloader has built-in shuffling.

In [13]:
# 0 will stand for no human and no dog. 1 will still for dog. 2 will stand for human and no dog.
# Defining my own dataloader based on the lists human_files and dog_files

from PIL import Image
from torchvision import transforms

data=[(f,2) for f in human_files[100:]]+[(f,1) for f in dog_files[100:]]+[(f,0) for f in caltech_files if f not in haar_faces]
np.random.shuffle(data)
split_index=int(len(data)*0.1) # 10% of data is reserved for validation
validation_files = data[:split_index]
training_files = data[split_index:]

normalize   = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                   std=[0.229, 0.224, 0.225])
unnormalize = transforms.Normalize(mean=-np.array(normalize.mean) * (1/np.array(normalize.std)),
                                   std=1/np.array(normalize.std))

testing_transformation = transforms.Compose([transforms.Resize((224,224)),
                                             transforms.ToTensor(),
                                             normalize])
training_transformation = transforms.Compose([transforms.RandomRotation(10),
                                             transforms.RandomResizedCrop(224,scale=(0.8,1)),
                                             transforms.ToTensor(),
                                             normalize])

def dataloader(files_labels, transformation, batch_size=32):
    """
    Returns a generator that yields pairs (torch tensor of batch of images,torch tensor of batch of labels)
    
    files_labels: A list of pairs consisting of an image filepath and an integer label
    transformation: A torchvision transforms transformation.
    """
    np.random.shuffle(files_labels)
    num_batches = int(len(files_labels)/batch_size)
    files_labels=files_labels[:num_batches*batch_size]
    for i in range(num_batches):
        this_batch = files_labels[i*batch_size:(i+1)*batch_size]
        list_of_images = []
        for file,_ in this_batch:
            try:
                img = transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
            except OSError:
                print(f"Image failed to load: {file}")
            list_of_images.append(img)
        images = torch.cat(list_of_images,dim=0)
        labels = torch.from_numpy(np.array([label for _,label in this_batch]))
        yield images,labels

Now let me just test out the data loader a bit below:

In [19]:
l=dataloader(training_files,training_transformation)
imgs,lbls=next(l)
plt.imshow((unnormalize(imgs[0]).permute(1,2,0)))
print(lbls[0].item())
0

Now to test that feedforward even works:

In [20]:
imgs,lbls=next(l)
if use_cuda:
    imgs=imgs.cuda()
    lbls=lbls.cuda()
torch.exp(human_dog_net(imgs[:1]))
Out[20]:
tensor([[0.3533, 0.3158, 0.3308]], device='cuda:0', grad_fn=<ExpBackward>)

Now for training

In [21]:
from torch import optim
import sys

optimizer=optim.SGD(human_dog_net.classifier.parameters(),lr=0.001)
loss_fn = nn.NLLLoss()

total_training_imgs=len(training_files)
total_validation_imgs=len(validation_files)
In [25]:
# If you don't want to wait for training, skip this cell, download the model I trained, and run the next cell instead.

epochs = 10
min_validation_loss=np.inf
for e in range(epochs):
    human_dog_net.train()
    total_loss = 0.
    imgs_processed = 0
    for imgs, lbls in dataloader(training_files,training_transformation):
        if use_cuda:
            imgs=imgs.cuda()
            lbls=lbls.cuda()
        optimizer.zero_grad()
        loss=loss_fn(human_dog_net(imgs),lbls)
        loss.backward()
        optimizer.step()
        total_loss += loss * imgs.shape[0]
        imgs_processed += imgs.shape[0]
        sys.stdout.write(f"{imgs_processed}/{total_training_imgs} images processed.\r")
        sys.stdout.flush()
    print(f"Epoch {e} done.                                   ")
    print(f"Training loss: {total_loss/imgs_processed}")
    human_dog_net.eval()
    total_loss = 0.
    num_correct=0
    imgs_processed = 0
    for imgs, lbls in dataloader(validation_files,testing_transformation):
        if use_cuda:
            imgs=imgs.cuda()
            lbls=lbls.cuda()
        with torch.no_grad():
            predictions=human_dog_net(imgs)
            num_correct+=torch.sum(predictions.argmax(1)==lbls).item()
            loss=loss_fn(predictions,lbls)
            total_loss += loss * imgs.shape[0]
            imgs_processed += imgs.shape[0]
        sys.stdout.write(f"{imgs_processed}/{total_validation_imgs} images processed.\r")
        sys.stdout.flush()
    validation_loss=total_loss/imgs_processed
    print(f"Validation loss: {validation_loss}\n")
    print(f"Validation accuracy: {100*num_correct/float(imgs_processed)}%\n")
    if validation_loss < min_validation_loss:
        torch.save(human_dog_net.state_dict(),'human_dog_net.pt')
        min_validation_loss = validation_loss
        
Epoch 0 done.                                   
Training loss: 0.011394654400646687
Validation loss: 0.00568950641900301

Validation accuracy: 99.86263736263736%

Epoch 1 done.                                   
Training loss: 0.009910529479384422
Validation loss: 0.004874031990766525

Validation accuracy: 99.86263736263736%

Epoch 2 done.                                   
Training loss: 0.008999381214380264
Validation loss: 0.0041347648948431015

Validation accuracy: 99.89697802197803%

Epoch 3 done.                                   
Training loss: 0.007845074869692326
Validation loss: 0.00365747744217515

Validation accuracy: 99.89697802197803%

Epoch 4 done.                                   
Training loss: 0.007502776570618153
Validation loss: 0.0032683357130736113

Validation accuracy: 99.96565934065934%

Epoch 5 done.                                   
Training loss: 0.006564196199178696
Validation loss: 0.002930378308519721

Validation accuracy: 99.93131868131869%

Epoch 6 done.                                   
Training loss: 0.006096938159316778
Validation loss: 0.0028560347855091095

Validation accuracy: 99.96565934065934%

Epoch 7 done.                                   
Training loss: 0.005779648199677467
Validation loss: 0.0026749547105282545

Validation accuracy: 99.96565934065934%

Epoch 8 done.                                   
Training loss: 0.005145913455635309
Validation loss: 0.002499210648238659

Validation accuracy: 99.96565934065934%

Epoch 9 done.                                   
Training loss: 0.004716898314654827
Validation loss: 0.0023371726274490356

Validation accuracy: 99.96565934065934%

In [22]:
human_dog_net.load_state_dict(torch.load('human_dog_net.pt', map_location='cuda' if use_cuda else 'cpu')) 
In [23]:
#Run this cell to just get validation accuracy

human_dog_net.eval()
total_loss = 0.
num_correct=0
imgs_processed = 0
for imgs, lbls in dataloader(validation_files,testing_transformation):
    if use_cuda:
        imgs=imgs.cuda()
        lbls=lbls.cuda()
    with torch.no_grad():
        predictions=human_dog_net(imgs)
        predictions.argmax(1)
        num_correct+=torch.sum(predictions.argmax(1)==lbls).item()
        loss=loss_fn(predictions,lbls)
        total_loss += loss * imgs.shape[0]
        imgs_processed += imgs.shape[0]
    sys.stdout.write(f"{imgs_processed}/{total_validation_imgs} images processed.\r")
    sys.stdout.flush()
print(f"Validation loss: {total_loss/imgs_processed}\n")
print(f"Validation accuracy: {100*num_correct/float(imgs_processed)}%\n")
Validation loss: 0.0036467036698013544

Validation accuracy: 99.93131868131869%

In [26]:
# Playing with the predictions. Keep running this cell and be amazed!
import random

human_dog_net.eval()

file,lbl = random.choice(validation_files)
img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
if use_cuda:
    img = img.cuda()
pred=human_dog_net(img).argmax().item()
img = img.cpu()
plt.imshow((unnormalize(img.squeeze(dim=0)).permute(1,2,0)))
idx2text={0:'No human, no dog',1:'Dog present',2:'Human present and no dog present'}
print(f"Prediction:{idx2text[pred]}\nLabel:{idx2text[lbl]}")
Prediction:No human, no dog
Label:No human, no dog
In [27]:
# Now let's try the initial 100 again since it's asked for in the instructions

# face_detector2 is my alternative face detector for this project.
def face_detector2(file):
    img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
    if use_cuda:
        img = img.cuda()
    human_dog_net.eval()
    return human_dog_net(img).argmax().item()==2

num_faces_human=0
bad_humans=[]
for file in tqdm(human_files_short):
    if face_detector2(file):
        num_faces_human += 1
    else:
        bad_humans.append(file)
num_faces_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
    if face_detector2(file):
        num_faces_dog += 1
        bad_dogs.append(file)

print(f"{num_faces_human}% of the first 100 human files have a detected human face.")
print(f"{num_faces_dog}% of the first 100 dog files have a detected human face.")
100%|██████████| 100/100 [00:03<00:00, 31.81it/s]
100%|██████████| 100/100 [00:05<00:00, 16.28it/s]
100% of the first 100 human files have a detected human face.
0% of the first 100 dog files have a detected human face.

Yay I have an improved face detector for the purposes of this project! It runs a lot slower, but that's fine. This isn't needed for processing lots of data-- users would only put in one image at a time, and for that accuracy is more valuable than saving a couple of seconds.


Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [28]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

Note to reader: The transforms used in the following implentation were defined up in the cell where I defined my dataloader for human_dog_net.

In [29]:
from PIL import Image
import torchvision.transforms as transforms

def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    
    VGG16.eval()
    img = testing_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
    if use_cuda:
        img = img.cuda()
    return VGG16(img).argmax().item() # predicted class index

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [30]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    prediction = VGG16_predict(img_path)
    return prediction>=151 and prediction<=268 # true/false

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: (My answer is printed in the output of the cell below.)

In [31]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

num_dogs_human=0
bad_humans=[]
for file in tqdm(human_files_short):
    if dog_detector(file):
        num_dogs_human += 1
        bad_humans.append(file)
num_dogs_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
    if dog_detector(file):
        num_dogs_dog += 1
    else:
        bad_dogs.append(file)

print(f"{num_dogs_human}% of the first 100 human files have a detected dog.")
print(f"{num_dogs_dog}% of the first 100 dog files have a detected dog.")
100%|██████████| 100/100 [00:03<00:00, 30.93it/s]
100%|██████████| 100/100 [00:05<00:00, 16.29it/s]
0% of the first 100 human files have a detected dog.
99% of the first 100 dog files have a detected dog.

I'm curious about any humans photos that triggered the dog detector! Let's see one:

In [32]:
imagenet_classes = pickle.load(open('imagenet1000_clsid_to_human.pkl','rb'))
for file in human_files:
    if dog_detector(file):
        plt.imshow(Image.open(file).convert('RGB'))
        plt.show()
        print(f"A \"{imagenet_classes[VGG16_predict(file)]}\" was detected in the above image.")
        break
A "Dandie Dinmont, Dandie Dinmont terrier" was detected in the above image.

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [33]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

Okay, my answer to the optional part of step 1 actually does include a dog detector! So let me go ahead define the dog detector portion of it and and and print the test results for that here.

(But I'm using VGG16 with just some additional training on my dataset, so I would not expect this to be much better than the using pretrained VGG16 directly as above).

In [34]:
# dog_detector2 is my alternative dog detector for this project.
def dog_detector2(file):
    img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
    if use_cuda:
        img = img.cuda()
    human_dog_net.eval()
    return human_dog_net(img).argmax().item()==1

num_dogs_human=0
bad_humans=[]
for file in tqdm(human_files_short):
    if dog_detector(file):
        num_dogs_human += 1
        bad_humans.append(file)
num_dogs_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
    if dog_detector(file):
        num_dogs_dog += 1
    else:
        bad_dogs.append(file)

print(f"{num_dogs_human}% of the first 100 human files have a detected dog.")
print(f"{num_dogs_dog}% of the first 100 dog files have a detected dog.")
100%|██████████| 100/100 [00:03<00:00, 32.45it/s]
100%|██████████| 100/100 [00:05<00:00, 16.25it/s]
0% of the first 100 human files have a detected dog.
99% of the first 100 dog files have a detected dog.


Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [1]:
import os,torch
from torchvision import datasets,transforms

### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes

image_size=192
batch_size=64

def randomCroppedRotateResize(max_angle,final_size):
    """A transformation that rotates the image by a random angle in range [-max_angle, +max_angle)
       then crops just enough to get rid of the empty black triangles in the border and resizes
       image to be a square of size final_size on each side. The angle should be given in degrees."""
    def f(img):
        angle=np.random.random()*2.0*max_angle-max_angle
        theta = np.abs(np.radians(angle))
        size_before_rot = final_size * (1+np.tan(theta))**2 / (1+np.tan(theta)**2)
        size_before_rot = int(size_before_rot+1)
        img=transforms.functional.resize(img,(size_before_rot,size_before_rot))
        img=transforms.functional.rotate(img,angle)
        img=transforms.functional.center_crop(img,final_size)
        return img
    return f


testing_transformation = transforms.Compose([transforms.Resize((image_size,image_size)),                                             
                                             transforms.ToTensor()])
training_transformation = transforms.Compose([
#                                               transforms.Resize((image_size,image_size)),
                                              randomCroppedRotateResize(10,image_size),
                                              transforms.RandomGrayscale(p=0.1),
                                              transforms.RandomHorizontalFlip(p=0.5),
                                              transforms.RandomVerticalFlip(p=0.5),
                                              transforms.ColorJitter(brightness=0.2,contrast=0.2),
                                              transforms.ToTensor(),
                                             ])

training_dataloader   = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/train/',transform=training_transformation),
    batch_size=batch_size,
    shuffle=True)
validation_dataloader = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/valid/',transform=testing_transformation),
    batch_size=batch_size)
test_dataloader       = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/test/',transform=testing_transformation),
    batch_size=batch_size)

loaders_scratch = {'train':training_dataloader,
                   'valid':validation_dataloader,
                   'test' :test_dataloader }

#just making sure of something here...
assert(training_dataloader.dataset.class_to_idx == validation_dataloader.dataset.class_to_idx)
assert(training_dataloader.dataset.class_to_idx == test_dataloader.dataset.class_to_idx)

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

How the code resizes: It uses a transformation I wrote randomCroppedRotateResize, which rotates the image by a random angle and the resizes the image down to image_size. The special thing about this transformation is that it actually does a crop as well, and it crops out exactly what it needs to in order to get rid of the black triangles that appear after a rotation. Bigger angles thus lead to bigger cropping, and I don't want to crop out any dogs so the angle is limited to $\pm 10^\circ$. The image_size is set to 192 for $192\times 192$ images. At first I tried 128, but after looking at the data myself (using the cell below) I decided that certain helpful finer features (such as fur textures) were being overly blurred for some dogs. I chose 192 specifically because I like powers of 2 (they make it easier for me to think through maxpooling steps): $192=3\cdot 2^6$. The size 256 is larger than I need, I think.

Other transformations: I chose to augment my data with a lot of different random transformations. The main reason is that I just don't have that much data for this task, and augmenting can allow me to train a more complex model without worrying as much about overfitting to a small data set.

  • The RandomGrayscale is there to prevent the model from relying too much on color all the time. Of course it will need to rely on color information a lot, but I want aspects of it to train that can get as much as possible without necessarily having color information. This is effectively like having dropout, except it's specifically focused on neurons that detect color.

  • The random horizantal and vertical flips are there because dogs are chirally symmetric objects, as far as I know. Vertical flips are maybe a bit more silly since people are likely to input upright dogs into this thing... but I'd like to go for as much robustness as possible against the rotational setup of the dog.

  • The small brightness and contrast variations should be harmless to feature detection and augment my data.

Normalization: I chose not to apply any normalization. transforms.ToTensor already forces things into the [0,1] range, and that's good enough for me.

In [132]:
#Look at some training data here
class_to_idx = training_dataloader.dataset.class_to_idx
idx_to_class = {idx:cls for cls,idx in class_to_idx.items()}
imgs,lbls=next(iter(training_dataloader))
plt.imshow((imgs[0].permute(1,2,0)))
print(idx_to_class[lbls[0].item()])
081.Greyhound

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [2]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        ## Define layers of a CNN
#         self.image_size=size
        
        self.conv1_1=nn.Conv2d(3,64,3,padding=1)
        
        self.conv2_1=nn.Conv2d(64,64,3,padding=1)

        self.lin1   =nn.Linear(65536,512)
        self.lin2   =nn.Linear(512,133)
                
        self.mp2 = nn.MaxPool2d(2,2)
        self.mp3 = nn.MaxPool2d(3,3)
        self.do = nn.Dropout(p=0.5)
        self.act= nn.ReLU()
    
    def forward(self, x):
        x=self.conv1_1(x)
        x=self.mp2(x)
        x=self.act(x)
        
        x=self.conv2_1(x)
        x=self.mp3(x)
        x=self.act(x)

        x=x.view(-1,65536)
        
        x=self.do(self.act(self.lin1(x)))
        x=nn.LogSoftmax(dim=1)(self.lin2(x))
        
        return x

#-#-# You do NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

My first approach was to try a scaled down version of VGG16. I know it of course needs to be scaled down, since I have a lot less data to work with than ImageNet! But I didn't scale it down nearly enough! It was training so slowly that I doubted my training code and loaded in MNIST data to test it on. It worked just fine on MNIST, so I guess it was just training really slowly on the dog images.

I finally scaled my model down enough to see some training progress, only to start overfitting like crazy. My model was still too huge for the data!

I continued to scale things down until I stopped seeing overfitting, until I was down to trying 2-3 convolutional layers followed by 1-2 fully connected layers. I imposed heavy dropout in the hidden linear layer to help fight the overfitting.

At that point I could continue to fine-tune the number of parameters in my model by

  • tuning the number of hidden layers in the fully connected part at the end,
  • tuning the number of feature maps (output channels) in my 2 or 3 convolutional layers, and
  • tuning the amount of maxpooling in the convolutional part (e.g. MaxPool2d(2,2) vs MaxPool2d(4,4)

But I couldn't get things quite right... I would either overfit (when I increase the number of parameters) or converge too early (when I allow too few parameters). The best I could get was 9% test accuracy.

At that point I looked up how to get $L_2$ regularization to work, and ended up reading documentation on the weight_decay hyperparameter in the SGD optimizer. (BTW I like SGD because I understand it. I might try different optimizers later, but I don't understand Adam yet, for example.)

I ended finding a happy-medium number of parameters where I got some overfitting, but only later in the training. Then I fixed that model and starting tuning weight_decay until I found a good value that didn't supress training too much and didn't let overfitting slip through so early on. The training still slips past the regularization and overfits eventually, but not before giving me a good enough model with 14% test accuracy! Yay?

The training output below shows the result of 100 epochs, but I actually trained for 180 just for fun. It didn't matter because overfitting had started by around epoch 40.

I think the main issue with training a CNN from scratch here is that we just have too little data to get the performance we want. It might be fine if there were just a handful of classes, but choosing correctly out of 133 classes requires a great deal of accuracy on the part of the model. Borrowing a diagram from the udacity notes,

we are in a situation where we have limited training data, and the data (while specific) is similar to the ImageNet type data. So we really should be doing transfer-learning in which almost the entire pretrained model is frozen!

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [3]:
import torch.optim as optim

### TODO: select loss function
criterion_scratch = nn.NLLLoss()

### TODO: select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters(),lr=0.02,momentum=0.9,weight_decay=0.002)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [4]:
from timeit import default_timer as timer
from datetime import timedelta
import numpy as np
import sys
In [17]:
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf 
    num_train_imgs=len(loaders['train'])*loaders['train'].batch_size
    num_valid_imgs=len(loaders['valid'])*loaders['valid'].batch_size
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        start_time = timer()
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## find the loss and update the model parameters accordingly
            ## record the average training loss, using something like
            ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            optimizer.zero_grad()
            loss=criterion(model(data),target)
            loss.backward()
            optimizer.step()
            train_loss += ((1 / (batch_idx + 1)) * (loss.item() - train_loss)) #this is clever!
            sys.stdout.write("Processed "+str(batch_idx*loaders['train'].batch_size)+'/'+str(num_train_imgs)+'  \r')
            sys.stdout.flush()
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        num_correct=0
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            with torch.no_grad():
                output=model(data)
                loss=criterion(output,target)
                num_correct+=torch.sum(output.argmax(1)==target).item()
                valid_loss += ((1 / (batch_idx + 1)) * (loss.item() - valid_loss))
            sys.stdout.write("Processed "+str(batch_idx*loaders['valid'].batch_size)+'/'+str(num_valid_imgs)+'  \r')
            sys.stdout.flush()

            
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}\t Validation Acc: {}'.format(
            epoch, 
            train_loss,
            valid_loss,
            num_correct/float(num_valid_imgs)
            ))
        
        ## TODO: save the model if validation loss has decreased
        if valid_loss<valid_loss_min:
            torch.save(model.state_dict(),save_path)
            valid_loss_min=valid_loss
            
        epoch_time = timer() - start_time
        print(f'That took {timedelta(seconds=epoch_time)}.\
              Estimated time remaining: {timedelta(seconds=epoch_time*(n_epochs-epoch))}\n')
            
    # return trained model
    return model
In [72]:
# train the model
model_scratch = train(180, loaders_scratch, model_scratch, optimizer_scratch, 
                      criterion_scratch, use_cuda, 'model_scratch.pt')

# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
Epoch: 1 	Training Loss: 4.882438 	Validation Loss: 4.895049	 Validation Acc: 0.010044642857142858
That took 0:03:00.358674.              Estimated time remaining: 4:57:35.508705

Epoch: 2 	Training Loss: 4.799894 	Validation Loss: 4.727750	 Validation Acc: 0.020089285714285716
That took 0:03:00.636074.              Estimated time remaining: 4:55:02.335278

Epoch: 3 	Training Loss: 4.657269 	Validation Loss: 4.591751	 Validation Acc: 0.018973214285714284
That took 0:03:00.195137.              Estimated time remaining: 4:51:18.928329

Epoch: 4 	Training Loss: 4.547812 	Validation Loss: 4.484006	 Validation Acc: 0.033482142857142856
That took 0:03:00.197360.              Estimated time remaining: 4:48:18.946519

Epoch: 5 	Training Loss: 4.499377 	Validation Loss: 4.472433	 Validation Acc: 0.03794642857142857
That took 0:03:00.262542.              Estimated time remaining: 4:45:24.941514

Epoch: 6 	Training Loss: 4.482910 	Validation Loss: 4.548023	 Validation Acc: 0.027901785714285716
That took 0:03:00.284060.              Estimated time remaining: 4:42:26.701597

Epoch: 7 	Training Loss: 4.431382 	Validation Loss: 4.485557	 Validation Acc: 0.033482142857142856
That took 0:02:59.659418.              Estimated time remaining: 4:38:28.325850

Epoch: 8 	Training Loss: 4.397876 	Validation Loss: 4.352545	 Validation Acc: 0.04352678571428571
That took 0:03:00.302233.              Estimated time remaining: 4:36:27.805450

Epoch: 9 	Training Loss: 4.381558 	Validation Loss: 4.360493	 Validation Acc: 0.044642857142857144
That took 0:02:59.452188.              Estimated time remaining: 4:32:10.149128

Epoch: 10 	Training Loss: 4.348361 	Validation Loss: 4.364795	 Validation Acc: 0.04352678571428571
That took 0:02:59.927626.              Estimated time remaining: 4:29:53.486343

Epoch: 11 	Training Loss: 4.317408 	Validation Loss: 4.297528	 Validation Acc: 0.05357142857142857
That took 0:03:00.056297.              Estimated time remaining: 4:27:05.010436

Epoch: 12 	Training Loss: 4.311917 	Validation Loss: 4.312478	 Validation Acc: 0.05357142857142857
That took 0:02:59.510308.              Estimated time remaining: 4:23:16.907138

Epoch: 13 	Training Loss: 4.308684 	Validation Loss: 4.258424	 Validation Acc: 0.06138392857142857
That took 0:03:00.036906.              Estimated time remaining: 4:21:03.210828

Epoch: 14 	Training Loss: 4.293016 	Validation Loss: 4.282295	 Validation Acc: 0.0625
That took 0:02:59.595802.              Estimated time remaining: 4:17:25.239002

Epoch: 15 	Training Loss: 4.259650 	Validation Loss: 4.210794	 Validation Acc: 0.06473214285714286
That took 0:02:59.756467.              Estimated time remaining: 4:14:39.299655

Epoch: 16 	Training Loss: 4.225864 	Validation Loss: 4.232643	 Validation Acc: 0.0703125
That took 0:02:59.676004.              Estimated time remaining: 4:11:32.784374

Epoch: 17 	Training Loss: 4.210868 	Validation Loss: 4.239957	 Validation Acc: 0.07142857142857142
That took 0:02:59.355990.              Estimated time remaining: 4:08:06.547188

Epoch: 18 	Training Loss: 4.194265 	Validation Loss: 4.209449	 Validation Acc: 0.07700892857142858
That took 0:02:59.831102.              Estimated time remaining: 4:05:46.150325

Epoch: 19 	Training Loss: 4.170469 	Validation Loss: 4.211861	 Validation Acc: 0.07142857142857142
That took 0:02:59.565998.              Estimated time remaining: 4:02:24.845860

Epoch: 20 	Training Loss: 4.134505 	Validation Loss: 4.133687	 Validation Acc: 0.06584821428571429
That took 0:02:59.923805.              Estimated time remaining: 3:59:53.904384

Epoch: 21 	Training Loss: 4.127600 	Validation Loss: 4.152079	 Validation Acc: 0.06919642857142858
That took 0:02:59.653098.              Estimated time remaining: 3:56:32.594739

Epoch: 22 	Training Loss: 4.084308 	Validation Loss: 4.184046	 Validation Acc: 0.07254464285714286
That took 0:02:59.698945.              Estimated time remaining: 3:53:36.517723

Epoch: 23 	Training Loss: 4.073870 	Validation Loss: 4.193833	 Validation Acc: 0.06808035714285714
That took 0:02:59.644331.              Estimated time remaining: 3:50:32.613487

Epoch: 24 	Training Loss: 4.065513 	Validation Loss: 4.212591	 Validation Acc: 0.06696428571428571
That took 0:02:59.722754.              Estimated time remaining: 3:47:38.929276

Epoch: 25 	Training Loss: 4.049393 	Validation Loss: 4.080518	 Validation Acc: 0.09040178571428571
That took 0:03:00.084174.              Estimated time remaining: 3:45:06.313051

Epoch: 26 	Training Loss: 4.012674 	Validation Loss: 4.134394	 Validation Acc: 0.06696428571428571
That took 0:02:59.789420.              Estimated time remaining: 3:41:44.417048

Epoch: 27 	Training Loss: 4.005612 	Validation Loss: 4.084571	 Validation Acc: 0.08705357142857142
That took 0:02:59.441512.              Estimated time remaining: 3:38:19.230394

Epoch: 28 	Training Loss: 3.968532 	Validation Loss: 4.119410	 Validation Acc: 0.08816964285714286
That took 0:02:59.494245.              Estimated time remaining: 3:35:23.585637

Epoch: 29 	Training Loss: 3.972935 	Validation Loss: 4.146888	 Validation Acc: 0.07924107142857142
That took 0:02:59.640000.              Estimated time remaining: 3:32:34.440000

Epoch: 30 	Training Loss: 3.933320 	Validation Loss: 4.065835	 Validation Acc: 0.07924107142857142
That took 0:03:00.232346.              Estimated time remaining: 3:30:16.264229

Epoch: 31 	Training Loss: 3.912233 	Validation Loss: 4.066232	 Validation Acc: 0.08258928571428571
That took 0:02:59.497494.              Estimated time remaining: 3:26:25.327077

Epoch: 32 	Training Loss: 3.901867 	Validation Loss: 4.024113	 Validation Acc: 0.078125
That took 0:02:59.990130.              Estimated time remaining: 3:23:59.328857

Epoch: 33 	Training Loss: 3.885337 	Validation Loss: 4.123932	 Validation Acc: 0.08816964285714286
That took 0:02:59.526487.              Estimated time remaining: 3:20:28.274611

Epoch: 34 	Training Loss: 3.852660 	Validation Loss: 3.960899	 Validation Acc: 0.08928571428571429
That took 0:02:59.990723.              Estimated time remaining: 3:17:59.387692

Epoch: 35 	Training Loss: 3.809422 	Validation Loss: 4.114091	 Validation Acc: 0.08147321428571429
That took 0:02:59.901083.              Estimated time remaining: 3:14:53.570400

Epoch: 36 	Training Loss: 3.827006 	Validation Loss: 4.060434	 Validation Acc: 0.08705357142857142
That took 0:02:59.492981.              Estimated time remaining: 3:11:27.550770

Epoch: 37 	Training Loss: 3.795178 	Validation Loss: 3.996418	 Validation Acc: 0.08482142857142858
That took 0:02:59.291615.              Estimated time remaining: 3:08:15.371750

Epoch: 38 	Training Loss: 3.742450 	Validation Loss: 4.065542	 Validation Acc: 0.09709821428571429
That took 0:02:59.408394.              Estimated time remaining: 3:05:23.320401

Epoch: 39 	Training Loss: 3.778416 	Validation Loss: 4.231737	 Validation Acc: 0.07700892857142858
That took 0:02:59.820454.              Estimated time remaining: 3:02:49.047692

Epoch: 40 	Training Loss: 3.775762 	Validation Loss: 4.136924	 Validation Acc: 0.10267857142857142
That took 0:02:59.786276.              Estimated time remaining: 2:59:47.176549

Epoch: 41 	Training Loss: 3.743884 	Validation Loss: 4.049572	 Validation Acc: 0.1015625
That took 0:02:59.319484.              Estimated time remaining: 2:56:19.849548

Epoch: 42 	Training Loss: 3.728895 	Validation Loss: 4.078631	 Validation Acc: 0.09486607142857142
That took 0:02:59.310758.              Estimated time remaining: 2:53:20.023980

Epoch: 43 	Training Loss: 3.672051 	Validation Loss: 3.927800	 Validation Acc: 0.10044642857142858
That took 0:03:00.162375.              Estimated time remaining: 2:51:09.255357

Epoch: 44 	Training Loss: 3.652853 	Validation Loss: 3.957703	 Validation Acc: 0.10044642857142858
That took 0:02:59.839675.              Estimated time remaining: 2:47:51.021804

Epoch: 45 	Training Loss: 3.650852 	Validation Loss: 4.057762	 Validation Acc: 0.10044642857142858
That took 0:02:59.632874.              Estimated time remaining: 2:44:39.808077

Epoch: 46 	Training Loss: 3.638545 	Validation Loss: 3.901363	 Validation Acc: 0.10602678571428571
That took 0:03:00.170847.              Estimated time remaining: 2:42:09.225752

Epoch: 47 	Training Loss: 3.608667 	Validation Loss: 4.023288	 Validation Acc: 0.10267857142857142
That took 0:02:59.815456.              Estimated time remaining: 2:38:50.219176

Epoch: 48 	Training Loss: 3.607070 	Validation Loss: 4.104963	 Validation Acc: 0.09151785714285714
That took 0:02:59.715294.              Estimated time remaining: 2:35:45.195266

Epoch: 49 	Training Loss: 3.577476 	Validation Loss: 4.026484	 Validation Acc: 0.10044642857142858
That took 0:02:59.589446.              Estimated time remaining: 2:32:39.061738

Epoch: 50 	Training Loss: 3.524221 	Validation Loss: 3.981263	 Validation Acc: 0.10825892857142858
That took 0:02:59.559808.              Estimated time remaining: 2:29:37.990411

Epoch: 51 	Training Loss: 3.541231 	Validation Loss: 3.946833	 Validation Acc: 0.11160714285714286
That took 0:02:59.927358.              Estimated time remaining: 2:26:56.440535

Epoch: 52 	Training Loss: 3.514808 	Validation Loss: 4.041649	 Validation Acc: 0.09263392857142858
That took 0:02:59.741966.              Estimated time remaining: 2:23:47.614364

Epoch: 53 	Training Loss: 3.497664 	Validation Loss: 3.993467	 Validation Acc: 0.09040178571428571
That took 0:02:59.799231.              Estimated time remaining: 2:20:50.563841

Epoch: 54 	Training Loss: 3.480188 	Validation Loss: 3.988637	 Validation Acc: 0.09263392857142858
That took 0:03:00.034544.              Estimated time remaining: 2:18:01.589003

Epoch: 55 	Training Loss: 3.454394 	Validation Loss: 4.042543	 Validation Acc: 0.10602678571428571
That took 0:03:01.373736.              Estimated time remaining: 2:16:01.818104

Epoch: 56 	Training Loss: 3.440348 	Validation Loss: 3.983409	 Validation Acc: 0.1015625
That took 0:03:01.049543.              Estimated time remaining: 2:12:46.179872

Epoch: 57 	Training Loss: 3.411114 	Validation Loss: 3.947035	 Validation Acc: 0.09486607142857142
That took 0:03:01.213921.              Estimated time remaining: 2:09:52.198606

Epoch: 58 	Training Loss: 3.422004 	Validation Loss: 4.064053	 Validation Acc: 0.09486607142857142
That took 0:03:00.948271.              Estimated time remaining: 2:06:39.827386

Epoch: 59 	Training Loss: 3.394098 	Validation Loss: 4.026036	 Validation Acc: 0.11049107142857142
That took 0:03:01.092470.              Estimated time remaining: 2:03:44.791272

Epoch: 60 	Training Loss: 3.340896 	Validation Loss: 3.986756	 Validation Acc: 0.10491071428571429
That took 0:03:00.884363.              Estimated time remaining: 2:00:35.374503

Epoch: 61 	Training Loss: 3.348642 	Validation Loss: 3.993886	 Validation Acc: 0.11383928571428571
That took 0:03:00.737662.              Estimated time remaining: 1:57:28.768836

Epoch: 62 	Training Loss: 3.332116 	Validation Loss: 3.906926	 Validation Acc: 0.10602678571428571
That took 0:03:01.014075.              Estimated time remaining: 1:54:38.534839

Epoch: 63 	Training Loss: 3.343967 	Validation Loss: 4.155456	 Validation Acc: 0.09821428571428571
That took 0:02:59.839886.              Estimated time remaining: 1:50:54.075779

Epoch: 64 	Training Loss: 3.298098 	Validation Loss: 3.957410	 Validation Acc: 0.11049107142857142
That took 0:02:59.528095.              Estimated time remaining: 1:47:43.011409

Epoch: 65 	Training Loss: 3.290707 	Validation Loss: 4.024427	 Validation Acc: 0.09040178571428571
That took 0:02:59.287897.              Estimated time remaining: 1:44:35.076390

Epoch: 66 	Training Loss: 3.270365 	Validation Loss: 3.903564	 Validation Acc: 0.10491071428571429
That took 0:02:59.201402.              Estimated time remaining: 1:41:32.847655

Epoch: 67 	Training Loss: 3.247718 	Validation Loss: 3.983163	 Validation Acc: 0.09709821428571429
That took 0:02:59.589823.              Estimated time remaining: 1:38:46.464143

Epoch: 68 	Training Loss: 3.221912 	Validation Loss: 3.902114	 Validation Acc: 0.11272321428571429
That took 0:03:00.089499.              Estimated time remaining: 1:36:02.863964

Epoch: 69 	Training Loss: 3.214198 	Validation Loss: 3.937417	 Validation Acc: 0.10714285714285714
That took 0:02:59.301271.              Estimated time remaining: 1:32:38.339416

Epoch: 70 	Training Loss: 3.234158 	Validation Loss: 3.930401	 Validation Acc: 0.09709821428571429
That took 0:02:59.682542.              Estimated time remaining: 1:29:50.476267

Epoch: 71 	Training Loss: 3.182494 	Validation Loss: 3.945205	 Validation Acc: 0.10491071428571429
That took 0:02:59.645713.              Estimated time remaining: 1:26:49.725691

Epoch: 72 	Training Loss: 3.151919 	Validation Loss: 4.053705	 Validation Acc: 0.10044642857142858
That took 0:02:59.457888.              Estimated time remaining: 1:23:44.820865

Epoch: 73 	Training Loss: 3.153051 	Validation Loss: 3.975544	 Validation Acc: 0.11049107142857142
That took 0:02:59.485475.              Estimated time remaining: 1:20:46.107831

Epoch: 74 	Training Loss: 3.167061 	Validation Loss: 4.024264	 Validation Acc: 0.09486607142857142
That took 0:02:59.627751.              Estimated time remaining: 1:17:50.321520

Epoch: 75 	Training Loss: 3.118069 	Validation Loss: 3.983085	 Validation Acc: 0.09709821428571429
That took 0:02:59.588659.              Estimated time remaining: 1:14:49.716463

Epoch: 76 	Training Loss: 3.123656 	Validation Loss: 4.018383	 Validation Acc: 0.10491071428571429
That took 0:02:59.105158.              Estimated time remaining: 1:11:38.523794

Epoch: 77 	Training Loss: 3.074463 	Validation Loss: 3.950764	 Validation Acc: 0.109375
That took 0:02:59.268770.              Estimated time remaining: 1:08:43.181716

Epoch: 78 	Training Loss: 3.054076 	Validation Loss: 3.961633	 Validation Acc: 0.09821428571428571
That took 0:02:59.515437.              Estimated time remaining: 1:05:49.339604

Epoch: 79 	Training Loss: 3.064825 	Validation Loss: 4.094785	 Validation Acc: 0.10825892857142858
That took 0:02:59.387920.              Estimated time remaining: 1:02:47.146321

Epoch: 80 	Training Loss: 3.070801 	Validation Loss: 3.966805	 Validation Acc: 0.11495535714285714
That took 0:02:59.415603.              Estimated time remaining: 0:59:48.312055

Epoch: 81 	Training Loss: 3.026165 	Validation Loss: 3.951436	 Validation Acc: 0.1171875
That took 0:02:59.532194.              Estimated time remaining: 0:56:51.111685

Epoch: 82 	Training Loss: 3.047485 	Validation Loss: 3.950311	 Validation Acc: 0.125
That took 0:02:59.369715.              Estimated time remaining: 0:53:48.654874

Epoch: 83 	Training Loss: 3.016188 	Validation Loss: 3.971285	 Validation Acc: 0.11049107142857142
That took 0:02:59.682447.              Estimated time remaining: 0:50:54.601601

Epoch: 84 	Training Loss: 2.990862 	Validation Loss: 3.925187	 Validation Acc: 0.12834821428571427
That took 0:02:59.353550.              Estimated time remaining: 0:47:49.656807

Epoch: 85 	Training Loss: 2.987201 	Validation Loss: 3.896477	 Validation Acc: 0.11272321428571429
That took 0:02:59.937183.              Estimated time remaining: 0:44:59.057751

Epoch: 86 	Training Loss: 2.919236 	Validation Loss: 4.059723	 Validation Acc: 0.10602678571428571
That took 0:02:59.535885.              Estimated time remaining: 0:41:53.502395

Epoch: 87 	Training Loss: 2.977914 	Validation Loss: 3.992355	 Validation Acc: 0.109375
That took 0:02:59.361961.              Estimated time remaining: 0:38:51.705498

Epoch: 88 	Training Loss: 2.941754 	Validation Loss: 4.009486	 Validation Acc: 0.11049107142857142
That took 0:02:59.576794.              Estimated time remaining: 0:35:54.921522

Epoch: 89 	Training Loss: 2.934778 	Validation Loss: 3.905842	 Validation Acc: 0.10825892857142858
That took 0:02:59.590405.              Estimated time remaining: 0:32:55.494455

Epoch: 90 	Training Loss: 2.921796 	Validation Loss: 4.015789	 Validation Acc: 0.11272321428571429
That took 0:02:59.559015.              Estimated time remaining: 0:29:55.590146

Epoch: 91 	Training Loss: 2.904349 	Validation Loss: 4.124495	 Validation Acc: 0.1015625
That took 0:02:59.654212.              Estimated time remaining: 0:26:56.887907

Epoch: 92 	Training Loss: 2.874784 	Validation Loss: 4.005938	 Validation Acc: 0.09709821428571429
That took 0:02:59.335805.              Estimated time remaining: 0:23:54.686440

Epoch: 93 	Training Loss: 2.916655 	Validation Loss: 4.040763	 Validation Acc: 0.12611607142857142
That took 0:02:59.293567.              Estimated time remaining: 0:20:55.054967

Epoch: 94 	Training Loss: 2.835108 	Validation Loss: 4.010260	 Validation Acc: 0.109375
That took 0:02:59.292697.              Estimated time remaining: 0:17:55.756183

Epoch: 95 	Training Loss: 2.880167 	Validation Loss: 4.010205	 Validation Acc: 0.11160714285714286
That took 0:02:59.881078.              Estimated time remaining: 0:14:59.405391

Epoch: 96 	Training Loss: 2.850210 	Validation Loss: 4.057804	 Validation Acc: 0.11941964285714286
That took 0:02:59.626003.              Estimated time remaining: 0:11:58.504013

Epoch: 97 	Training Loss: 2.835165 	Validation Loss: 4.089802	 Validation Acc: 0.09709821428571429
That took 0:03:00.305626.              Estimated time remaining: 0:09:00.916877

Epoch: 98 	Training Loss: 2.802127 	Validation Loss: 3.945311	 Validation Acc: 0.12611607142857142
That took 0:03:00.048214.              Estimated time remaining: 0:06:00.096428

Epoch: 99 	Training Loss: 2.847643 	Validation Loss: 3.991116	 Validation Acc: 0.10267857142857142
That took 0:03:00.249810.              Estimated time remaining: 0:03:00.249810

Epoch: 100 	Training Loss: 2.819792 	Validation Loss: 3.911015	 Validation Acc: 0.12165178571428571
That took 0:03:00.047481.              Estimated time remaining: 0:00:00

In [5]:
# I run this cell when I want to load the model without having to retrain it.
model_scratch.load_state_dict(torch.load('model_scratch.pt'))

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [6]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))

# call test function    
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.912861


Test Accuracy: 14% (119/836)
In [210]:
# Setting up to play with model:

class_to_idx = test_dataloader.dataset.class_to_idx
idx_to_class = {idx:cls for cls,idx in class_to_idx.items()}
l=iter(test_dataloader)
In [219]:
# Play with model:

imgs,lbls=next(l)
ii=np.random.randint(0,imgs.shape[0]-1)
img=imgs[ii]
lbl=lbls[ii]
plt.imshow((img.permute(1,2,0)))
if use_cuda: img=img.cuda()
with torch.no_grad():
    pred=torch.exp(model_scratch(img.unsqueeze(dim=0)))
probabilities,classes=pred.squeeze().topk(5,sorted=True)
classes=classes.cpu()
print("Actual breed: "+str(idx_to_class[lbl.item()]))
class_names = [idx_to_class[idx] for idx in classes.data.numpy().tolist()]
print("Top 5 predictions in order:\n"+str(class_names))
Actual breed: 077.Gordon_setter
Top 5 predictions in order:
['056.Dachshund', '022.Belgian_tervuren', '077.Gordon_setter', '035.Boykin_spaniel', '098.Leonberger']

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [181]:
## TODO: Specify data loaders

# I like my data loaders from earlier but the image size needs to be made compatible for VGG,
# so I am copying the code and only modifying image_size
# and adding the normalization that VGG was trained on

image_size=224
batch_size=64

normalize   = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                   std=[0.229, 0.224, 0.225])
unnormalize = transforms.Normalize(mean=-np.array(normalize.mean) * (1/np.array(normalize.std)),
                                   std=1/np.array(normalize.std))

testing_transformation = transforms.Compose([transforms.Resize((image_size,image_size)),                                             
                                             transforms.ToTensor(),
                                             normalize,])
training_transformation = transforms.Compose([
#                                               transforms.Resize((image_size,image_size)),
                                              randomCroppedRotateResize(10,image_size),
                                              transforms.RandomGrayscale(p=0.1),
                                              transforms.RandomHorizontalFlip(p=0.5),
                                              transforms.RandomVerticalFlip(p=0.5),
                                              transforms.ColorJitter(brightness=0.2,contrast=0.2),
                                              transforms.ToTensor(),
                                              normalize,
                                             ])

training_dataloader   = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/train/',transform=training_transformation),
    batch_size=batch_size,
    shuffle=True)
validation_dataloader = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/valid/',transform=testing_transformation),
    batch_size=batch_size)
test_dataloader       = torch.utils.data.DataLoader(
    datasets.ImageFolder('dogImages/test/',transform=testing_transformation),
    batch_size=batch_size)

loaders_transfer = {'train':training_dataloader,
                    'valid':validation_dataloader,
                    'test' :test_dataloader }

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [182]:
import torchvision.models as models
import torch.nn as nn

# check if CUDA is available
use_cuda = torch.cuda.is_available()

## TODO: Specify model architecture 

model_transfer = models.vgg16(pretrained=True)

if use_cuda:
    model_transfer = model_transfer.cuda()
    
# Freeze parameters in convolutional layers:
for module in model_transfer.features:
    for param in module.parameters():
        param.requires_grad = False

#Look at classifier layers:
model_transfer.classifier
Out[182]:
Sequential(
  (0): Linear(in_features=25088, out_features=4096, bias=True)
  (1): ReLU(inplace)
  (2): Dropout(p=0.5)
  (3): Linear(in_features=4096, out_features=4096, bias=True)
  (4): ReLU(inplace)
  (5): Dropout(p=0.5)
  (6): Linear(in_features=4096, out_features=1000, bias=True)
)
In [183]:
# Freeze parameters in the first fully connected layer:
for param in model_transfer.classifier[0].parameters():
    param.requires_grad = False

# Re-initialize the last two fully connected layers with 512 hidden nodes and 133 output nodes
model_transfer.classifier[3]=nn.Linear(4096,512).to('cuda' if use_cuda else 'cpu')
model_transfer.classifier[6]=nn.Linear(512,133).to('cuda' if use_cuda else 'cpu')

# Replace dropout by batch normalization-- I had more success with it.
model_transfer.classifier[2]=nn.BatchNorm1d(4096).to('cuda' if use_cuda else 'cpu')
model_transfer.classifier[5]=nn.BatchNorm1d(512 ).to('cuda' if use_cuda else 'cpu')

# Tack on a log softmax at the end, because I like doing things this way
model_transfer.classifier.add_module("7",nn.LogSoftmax(dim=1))

# Look at the entire thing to make sure things are as expected:
model_transfer
Out[183]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): BatchNorm1d(4096, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (3): Linear(in_features=4096, out_features=512, bias=True)
    (4): ReLU(inplace)
    (5): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (6): Linear(in_features=512, out_features=133, bias=True)
    (7): LogSoftmax()
  )
)

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: For reasons outlined at the end of my answer to question 4, I expect some success from an approach in which I only train the last one or two fully connected layers of the pretrained VGG16. I also should randomize the weights in the layer I'm going to train, to gain the general benefits of well-initialized weights.

Intuitively, the layers of VGG16 are already very good at extracting features from images. My model can learn to classify dog breeds based on these features, rather than also having to learn feature extraction itself. The resulting model will be bigger than it needs to be, since VGG16 extracts a lot of features that are probably irrelevant to dog breed. But it will train much faster and gain higher accuracy than I can get from my small dog breed dataset.

I experimented with the following setups:

  • Training only the last fully connected layer while freezing everything else
  • Training only the last two fully connected layers while freezing everything else
    • Various numbers of hidden nodes between the last two layers
  • Various weight_decay choices in the optimizer, to fight overfitting
  • Using batch normalization vs dropout

I ended up finding that batch normalization worked incredibly well, and that I could get lower validation loss by training the last two hidden layers rather than just one, and that a relatively small number of hidden nodes prevented early overfitting during training.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [184]:
import torch.optim as optim

criterion_transfer = nn.NLLLoss()
optimizer_transfer = optim.SGD(model_transfer.parameters(),lr=0.02,momentum=0.9)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [185]:
# train the model
model_transfer = train(10, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')
Epoch: 1 	Training Loss: 2.512653 	Validation Loss: 0.845388	 Validation Acc: 0.71875
That took 0:04:06.234468.              Estimated time remaining: 0:36:56.110213

Epoch: 2 	Training Loss: 1.253245 	Validation Loss: 0.697496	 Validation Acc: 0.7589285714285714
That took 0:04:06.552513.              Estimated time remaining: 0:32:52.420106

Epoch: 3 	Training Loss: 0.980519 	Validation Loss: 0.650254	 Validation Acc: 0.7578125
That took 0:04:06.313359.              Estimated time remaining: 0:28:44.193510

Epoch: 4 	Training Loss: 0.855023 	Validation Loss: 0.600678	 Validation Acc: 0.7667410714285714
That took 0:04:06.307332.              Estimated time remaining: 0:24:37.843991

Epoch: 5 	Training Loss: 0.739459 	Validation Loss: 0.730507	 Validation Acc: 0.75
That took 0:04:02.272438.              Estimated time remaining: 0:20:11.362188

Epoch: 6 	Training Loss: 0.672653 	Validation Loss: 0.601585	 Validation Acc: 0.765625
That took 0:04:02.688006.              Estimated time remaining: 0:16:10.752024

Epoch: 7 	Training Loss: 0.566576 	Validation Loss: 0.631675	 Validation Acc: 0.7544642857142857
That took 0:04:01.637370.              Estimated time remaining: 0:12:04.912109

Epoch: 8 	Training Loss: 0.514480 	Validation Loss: 0.638193	 Validation Acc: 0.7589285714285714
That took 0:04:02.019445.              Estimated time remaining: 0:08:04.038890

Epoch: 9 	Training Loss: 0.472826 	Validation Loss: 0.696238	 Validation Acc: 0.75
That took 0:04:02.470417.              Estimated time remaining: 0:04:02.470417

Epoch: 10 	Training Loss: 0.459925 	Validation Loss: 0.660417	 Validation Acc: 0.7555803571428571
That took 0:04:01.967452.              Estimated time remaining: 0:00:00

In [186]:
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [187]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 0.637050


Test Accuracy: 81% (681/836)
In [198]:
threshold = 1 # If the probability on the prediction is below this, we'd like to report the top k predictions.
# (this threshold is giving me info for the flask app I worked out outside of this notebook,
#  I changed it to 1 here to give accurate "topk" accuracies)

test_loss = 0.
correct = [0]*5
total = 0

model_transfer.eval()
for batch_idx, (data, target) in enumerate(loaders_transfer['test']):
    if use_cuda:
        data, target = data.cuda(), target.cuda()
    with torch.no_grad():
        output = model_transfer(data)
        loss = criterion_transfer(output, target)
    test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
    top5_logprobs, top5_indices = output.topk(5,dim=1,sorted=True)
    top5_probs=torch.exp(top5_logprobs)
    for n in range(top5_probs.shape[0]):
        top_prob=top5_probs[n][0].item()
        indices_list = top5_indices[n].cpu().numpy().tolist() 
        if target[n].item()==top5_indices[n][0].item():
            for i in range(len(correct)): correct[i] += 1
        elif top_prob<threshold and target[n].item() in indices_list:
            for i in range(indices_list.index(target[n].item()),len(correct)): correct[i] += 1
    total += data.size(0)

print('Test Loss: {:.6f}\n'.format(test_loss))

print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
    100. * correct[0] / total, correct[0], total))

for i in range(1,len(correct)):
    print('\nTest \"Top %d\" Accuracy: %2d%% (%2d/%2d)' % (
        i+1,100. * correct[i] / total, correct[i], total))
Test Loss: 0.637050


Test Accuracy: 81% (681/836)

Test "Top 2" Accuracy: 91% (767/836)

Test "Top 3" Accuracy: 95% (798/836)

Test "Top 4" Accuracy: 97% (816/836)

Test "Top 5" Accuracy: 98% (821/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [199]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from PIL import Image

class_to_idx = training_dataloader.dataset.class_to_idx
idx_to_class = {idx:(cls[4:].replace("_", " ")) for cls,idx in class_to_idx.items()}
pickle.dump(idx_to_class, open( "idx_to_class.p", "wb" )) # this will be handy to have in the flask app

def predict_breed_transfer(img_path):
    img = testing_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
    if use_cuda: img=img.cuda()
    model_transfer.eval()
    with torch.no_grad():
        output = model_transfer(img)
    return idx_to_class[output.squeeze(dim=0).argmax().item()]
In [175]:
# Setting up to play with model:
l=iter(test_dataloader)
In [196]:
# Play with model:
imgs,lbls=next(l)
ii=np.random.randint(0,imgs.shape[0]-1)
img=imgs[ii]
lbl=lbls[ii]
plt.imshow((unnormalize(img).permute(1,2,0)))
if use_cuda: img=img.cuda()
with torch.no_grad():
    pred=torch.exp(model_transfer(img.unsqueeze(dim=0)))

probabilities,classes=pred.squeeze().topk(5,sorted=True)
classes=classes.cpu()
print("Actual breed: "+str(idx_to_class[lbl.item()]))
class_names = [idx_to_class[idx] for idx in classes.data.numpy().tolist()]
print("Top 5 predictions in order:\n"+str(class_names))
Actual breed: English toy spaniel
Top 5 predictions in order:
['Cavalier king charles spaniel', 'English toy spaniel', 'English springer spaniel', 'Welsh springer spaniel', 'Japanese chin']

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [179]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

human_dog_net_transformation = transforms.Compose([transforms.Resize((224,224)),
                                                   transforms.ToTensor(),
                                                   normalize])

def run_app(img_path):
    img = human_dog_net_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
    plt.imshow((unnormalize(img.squeeze(dim=0)).permute(1,2,0)))
    plt.show()
    if use_cuda: img = img.cuda()
    human_dog_net.eval()
    with torch.no_grad():
        human_dog_presence = human_dog_net(img).argmax().item()
    if human_dog_presence == 0:
        print("I can't find the dog in this image.")
        return -1
    elif human_dog_presence == 1:
        print("I'm pretty sure that's a ...")
    elif human_dog_presence == 2:
        print("I can't find a dog, but there does seem to be a human in this image!")
        print("The image most closely resembles a ...")
    print(predict_breed_transfer(img_path)+'.')
    return 0
        
    

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: Since my expectations were pretty much crushed by the attempt to create a good model from scratch, I ended up being very impressed with the final model created with transfer learning. Some improvement ideas:

  • I think the algorithm here should show more than just the top choice of dog breed, and if the probability on the top choice is low then I think this should be mentioned to the user!
  • Sometimes my dog detector misses the dog when the dog in an image is not very prominent. A better sort of dog detector would actually be a dog-finder that then crops the image to the dog it found and then feeds the cropped dog to the dog breed classifier.
  • Finally, I think the best way to continue improving this algorithm is to get a hold of more dog breed training data! Overfitting was pretty much the main limitation to training a better model.
In [180]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
run_app('sample_images/01.jpg')
print("(The website I pulled this from said that this is an English Sheepdog/Wirehaired Fox Terrier Mix.)")

run_app('sample_images/02.jpg')
print("(As you can see, this is a stuffed toy version of the taco bell chihuahua.)")

run_app('sample_images/03.jpg')
print("(A very nice clear photo of a labrador retriever.)")

run_app('sample_images/04.png')
print("(Jake the dog.)")

run_app('sample_images/05.jpg')
print("(I'm trying to throw off the dog_detector. I don't know what the actual breed is.)")

#Let's do five random humans for fun
for _ in range(5):
    run_app(random.choice(human_files))
I'm pretty sure that's a ...
Dandie dinmont terrier.
(The website I pulled this from said that this is an English Sheepdog/Wirehaired Fox Terrier Mix.)
I can't find the dog in this image.
(As you can see, this is a stuffed toy version of the taco bell chihuahua.)
I'm pretty sure that's a ...
Labrador retriever.
(A very nice clear photo of a labrador retriever.)
I can't find the dog in this image.
(Jake the dog.)
I'm pretty sure that's a ...
Golden retriever.
(I'm trying to throw off the dog_detector. I don't know what the actual breed is.)
I can't find a dog, but there does seem to be a human in this image!
The image most closely resembles a ...
Chihuahua.
I can't find a dog, but there does seem to be a human in this image!
The image most closely resembles a ...
Glen of imaal terrier.
I can't find a dog, but there does seem to be a human in this image!
The image most closely resembles a ...
Wirehaired pointing griffon.
I can't find a dog, but there does seem to be a human in this image!
The image most closely resembles a ...
Affenpinscher.
I can't find a dog, but there does seem to be a human in this image!
The image most closely resembles a ...
Pharaoh hound.